<?php

/**
 * Created By PhpStorm
 * User sclecon
 * Contact Email 27941662@qq.com
 * Time 2021/9/7 11:08
 */


namespace wowo;


use wowo\Db\DbBase;

class Db extends DbBase
{

    public function add(array $data = []){
        if (is_array($data) && $data){
            $this->data($data);
        }
        if (count($data) == count($data, 1)){
            return $this->insert();
        }else{
            $structure = $this->structureInsert();
            return $this->exec($structure);
        }
    }

    public function save(array $data = [], $id = false){
        if (is_array($data) && $data){
            $this->data($data);
        }
        if ($id){
            $this->where(['id'=>$id]);
        }
        return $this->structureUpdate();
    }

    public function column($field, $pk = false){
        if ($pk){$this->setPk($pk);}
        $this->field($field.','.$this->pk);
        $structure = $this->structure();
        $response = $this->query($structure['sql'], $structure['params']);
        $datalist = [];
        foreach ($response as $item){
            $datalist[$item['uid']] = $item['username'];
        }
        return $datalist;
    }

    public function value($field){
        $this->field($field);
        $structure = $this->structure();
        $response = $this->query($structure['sql'], $structure['params']);
        return $response[0][$field];
    }

    public function find($condition = false){
        if ($condition !== false){
            if (is_int($condition) or intval($condition) == $condition){
                $condition = [$this->pk => $condition];
            }
            $this->where($condition);
        }
        $structure = $this->structure();
        $response = $this->query($structure['sql'], $structure['params']);
        return $response[0];
    }

    public function all(){
        $structure = $this->structure();
        return $this->query($structure['sql'], $structure['params']);
    }

    public function count(){
        $this->field('count(*) as sum');
        $structure = $this->structure();
        $response = $this->query($structure['sql'], $structure['params']);
        return $response[0]['sum'];
    }

    public function del($condition = false){
        if ($condition !== false){
            if (is_int($condition) or intval($condition) == $condition){
                $condition = [$this->pk => $condition];
            }
            $this->where($condition);
        }
        $structure = $this->delWhereStructures();
        return $this->exec($structure['sql'], $structure['params']);

        wowohalt($this->delWhereStructures());


        $structure = 'delete from '.$this->table.$this->delWhereStructure();
        wowohalt($structure);
        return $this->exec($structure);
    }
}